﻿using Kingdee.BOS.App.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.SerivesPlugin.Dz
{
    [Description("Dz：BeforeDoSaveExecute"), HotUpdate]
    public class DzBeforeDoSaveExecute : AbstractOperationServicePlugIn
    {
        public override void BeforeDoSaveExecute(BeforeDoSaveExecuteEventArgs e)
        {
            base.BeforeDoSaveExecute(e);
            var obj = e.DataEntities;
            Field dhwb = this.BusinessInfo.GetField("FEntryNote");
            //dhwb.PropertyName = "fjfj";
            foreach (var entity in obj)
            {
                DynamicObjectCollection rows = entity["BillEntry"] as DynamicObjectCollection;
                foreach (var row in rows)
                {
                    row[dhwb.PropertyName] = "这是多行文本";
                    //row["EntryNote"] = "这是多行文本的备注";
                }
            }
            // 保存前，提前填充主键数据
            var seqReader = new SequenceReader(this.Context);
            seqReader.AutoSetPrimaryKey(e.DataEntities, e.DataEntities[0].DynamicObjectType);

            // 保存前，提前生成单据编号
            var billNoFiled = this.BusinessInfo.GetBillNoField();
            if (billNoFiled == null)
            {
                return;
            }
            var options = new Dictionary<string, object>();
            options["CodeTime"] = 1;
            options["UpdateMaxNum"] = 1;
            var service = new BusinessDataService();
            var billNos = service.GetBillNo(this.Context, this.BusinessInfo, e.DataEntities, options);
            if (billNos != null && billNos.Count == e.DataEntities.Length)
            {
                for (var i = 0; i < e.DataEntities.Length; i++)
                {
                    if (!string.IsNullOrEmpty(billNos[i].BillNo))
                    {
                        var prefix = (billNos[i].BillNo.StartsWith("XXX-") ? "" : "XXX-");
                        e.DataEntities[i][billNoFiled.PropertyName] = prefix + billNos[i].BillNo;
                    }
                }
            }
        }
    }
}
